import { Coupon } from './coupon-model.js';
var util = require ('../../utils/util.js');
var coupon = new Coupon();
Page({

  data: {
    dataArr: [],
    type: ["未使用","已使用","已失效"],
    currentTpye: 0,
    page: 1,
    hiddenNomore: true,
    hiddenLoading: true,
    hiddenNullData: true,
    onLoading: false,
    nomore: false,
  },
  onLoad: function(options) {
    var index = options.index ? options.index : 0;
    this._loadData(index);
  },
  //加载卡券数据
  _loadData: function(index) {
    this.setData({
      currentTpye: index
    })
    this._getData();
  },
  //顶部选项卡切换
  typeTap: function(e) {
    var curType = e.currentTarget.dataset.index;
    this.data.currentTpye = curType
    this.setData({
      dataArr : [],
      hiddenNomore:true,
      hiddenNullData: true,
      currentTpye: curType
    });
    this.data.nomore = false;
    this.data.page = 1;
    this._getData();
  },
  /*获取卡券列表*/
  _getData: function() {
    var that = this;
    var args = {
      page: this.data.page,
      number:10,
      coupon_status: that.data.currentTpye
    }
    that.setData({
      loadingHidden: false
    })
    coupon.getMyCoupons(args, (res) => {
      var items = res.items;
      if (!items || items.length < res._meta.perPage) {
        this.data.loadMore = false;
      }
      items = that.data.dataArr.concat(items);
      that.setData({
        dataArr:items
      })
      //隐藏正在加载中
      that.setData({
        hiddenLoading: true
      })
      if (items.length == 0) {
        //显示没有数据
        that.setData({
          hiddenNullData: false
        })
      }
      if (that.data.page >= res._meta.pageCount) {
        that.data.nomore = true;
        if (that.data.page > 1) {
          //显示没有更多
          that.setData({
            hiddenNomore: false
          })
        }
      }
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.nomore) {
      return false;
    }
    this.data.page ++;
    this._getData();
  },
  //跳转到卡券详情
  toDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'detail?type=use&id='+id
    })
  },
  //使用优惠券

  use: function (e) {
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    if(type == 0){
      var url = '../product/list'
    }else if(type == 1) {
      var url = '../product/product?id=' + id
    } else if (type == 2) {
      var url = '../product/list?cate_id=' + id
    }
    wx.navigateTo({
      url: url
    })
  },
  //自定义底部跳转
  footRedirect: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.switchTab({
      url: url,
    })
  }
})